package com.beiben.utils;

import java.lang.reflect.Field;
import java.util.Comparator;

/**
 * Created by admin on 2021/1/15.
 */
public class SortComparator<T> implements Comparator<T> {

    private final int ToRight = 1;

    private final int ToLeft = -1;

    @Override
    public int compare(T o1, T o2) {
        String str1 = null;
        String str2 = null;
        Field sortFile = null;
        try {
            sortFile = o1.getClass().getDeclaredField("serial");
            sortFile.setAccessible(true);
            Object o4 = sortFile.get(o1);
            str1 = o4 == null ? "0" : o4.toString();
            Object o3 = sortFile.get(o2);
            str2 = o3 == null ? "0" : o3.toString();
        } catch (NoSuchFieldException | IllegalAccessException e) {
        }
        String[] str1Split = str1.split("\\.");
        String[] str2Split = str2.split("\\.");
        int minSplitLength = str1Split.length > str2Split.length
                ? str2Split.length : str1Split.length;
        // 用长度小的数组长度作为遍历边界，防止数组越界
        for (int i = 0; i < minSplitLength; i++) {
            // 将字符串转换成数字解决 一位数字(eg: 2) 和 两位数字(eg: 10) 的大小比较问题
            Integer strToInt1 = Integer.valueOf(str1Split[i]);
            Integer strToInt2 = Integer.valueOf(str2Split[i]);
            int compareResult = strToInt1.compareTo(strToInt2);
            if (compareResult == 0) {
                continue;
            } else if (compareResult > 0) {
                return ToRight;
            } else if (compareResult < 0) {
                return ToLeft;
            }
        }
        // 若程序进行到这里，说明在循环里没有得出比较结果。
        // 此时应该是数组长度长的字符串（1.10.1）排在后面，数组长度短的字符串（1.10）排在前面
        if (minSplitLength == str1Split.length) {
            return ToLeft;
        } else {
            return ToRight;
        }
    }
}
